<?php

namespace app\admin\controller\oil\order;

use addons\sum\library\Export;
use addons\sum\model\Config as ModelConfig;
use app\admin\model\sum\user\User;
use think\Db;
use think\Config;
use app\common\controller\Backend;
use app\admin\controller\sum\Base;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Base
{
    protected $noNeedRight = ['getType', 'getExpress'];

    /**
     * Order模型对象
     * @var \app\admin\model\oil\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();

        // 手动加载语言包

        $this->model = new \app\admin\model\oil\order\Order;
        $this->storeModel = new \app\admin\model\oil\Store;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
        $this->view->assign("platformList", $this->model->getPlatformList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 订单导出
     */
    public function export()
    {
        $nobuildfields = ['status', 'aftersale_sn', 'dispatch_type', 'goods_type', 'nickname', 'user_phone', 'goods_title', 'store_id'];
        list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);
        $expCellName = [
            'id' => 'ID',
            'order_sn' => '订单号',
            'createtime_text' => '下单时间',
            'fuel_name' => '油品',
            'fuel_price' => '价格',
            'litre' => '油量',
            'user_name' => '下单用户',
            'refund_status_text' => '退款状态',
            'aftersale_status_text' => '售后状态',
            'status_text' => '订单状态',
            'hexiao_text' => '核销状态',
            'store_name' => '油站',
            'goods_amount' => '订单金额',
            'discount_fee' => '优惠金额',
            'total_amount' => '优惠后金额',
            'total_fee' => '需支付金额',
            'dispatch_amount' => '车队服务费',
            'refund_time_text' => '退款完成时间',
        ];
        $export = new Export();
        $spreadsheet = null;
        $sheet = null;

        $total = $this->buildSearchOrder()
            ->where($where)
            ->removeOption('soft_delete')
            ->order($sort, $order)
            ->count();

        $current_total = 0;     // 当前已循环条数
        $page_size = 2000;
        $total_page = intval(ceil($total / $page_size));
        if ($total == 0) {
            $this->error('导出数据为空');
        }
        for ($i = 0; $i < $total_page; $i++) {
            $page = $i + 1;
            $is_last_page = ($page == $total_page) ? true : false;
            $list = $this->buildSearchOrder()
                ->where($where)
                ->with(['user'])
                ->order($sort, $order)
                ->limit(($i * $page_size), $page_size)
                ->select();

            $list = collection($list)->toArray();
            $current_total += count($list);     // 当前循环总条数
            $export->exportExcel('订单列表-' . date('Y-m-d H:i:s'), $expCellName, $list, $spreadsheet, $sheet, [
                'page' => $page,
                'current_total' => $current_total,
                'is_last_page' => $is_last_page
            ]);
        }
    }

    /**
     * 查看列表
     */
    public function index()
    {
//        $store_map=[];
//        if (!$this->auth->isSuperAdmin()) {//不是超级管理员只能查看自己有站的订单
//            $admin_id=$this->auth->id;
//            $store_ids=Db::name('oil_store')->where('admin_id',$admin_id)->column('id');
//            if(is_array($store_ids)){
//                $store_map['store_id']=['in',$store_ids];
//            }
//        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $nobuildfields = ['status', 'aftersale_sn', 'dispatch_type', 'goods_type', 'nickname', 'user_phone', 'goods_title', 'store_id'];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);

            $total = $this->buildSearchOrder()
                ->where($where)
//                ->where($store_map)
                ->removeOption('soft_delete')
                ->order($sort, $order)
                ->count();

            $list = $this->buildSearchOrder()
                ->where($where)
//                ->where($store_map)
                ->with(['user'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();

//            $store_ids = array_unique(array_column($items, 'store_id'));
//            $stores = $this->storeModel->where('id', 'in', $store_ids)->select();
//            $stores = collection($stores)->toArray();
//            $stores = array_column($stores, null, 'id');
//
//            foreach ($list as $key => $od) {
//                foreach ($od['item'] as $k => $it) {
//                    $list[$key]['item'][$k]['store'] = $stores[$it['store_id']] ?? null;
//                }
//            }

            $result = array("total" => $total, "rows" => $list);

            return $this->success('操作成功', null, $result);
        }
        return $this->view->fetch();
    }


    // 获取要查询的订单类型
    public function getType()
    {
        $type = $this->model->getTypeList();
        $pay_type = $this->model->getPayTypeList();
        $platform = $this->model->getPlatformList();

        $result = [
            'type' => $type,
            'pay_type' => $pay_type,
            'platform' => $platform,
        ];
        $data = [];
        foreach ($result as $key => $list) {
            $data[$key][] = ['name' => '全部', 'type' => 'all'];
            foreach ($list as $k => $v) {
                $data[$key][] = [
                    'name' => $v,
                    'type' => $k
                ];
            }
        }
        return $this->success('操作成功', null, $data);
    }


    // 订单详情
    public function detail($id)
    {
        if ($this->request->isAjax()) {
            $row = $this->model->withTrashed()->with(['user'])->where('id', $id)->find();
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            return $this->success('获取成功', null, [
                'order' => $row,
            ]);
        }
        $this->assignconfig('id', $id);
        return $this->view->fetch();
    }

    /**
     * 同意退款
     */
    public function refund($id = 0, $item_id = 0)
    {
        if ($this->request->isAjax()) {
            $refund_money = round($this->request->post('refund_money', 0), 2);

            if ($refund_money < 0) {
                $this->error('退款金额不能小于 0');
            }

            $order = $this->model->where(
                'status',
                'in',
                [
                    \app\admin\model\oil\order\Order::STATUS_PAYED,
                    \app\admin\model\oil\order\Order::STATUS_FINISH
                ]
            )->where('id', $id)->find();

            if (!$order) {
                $this->error('订单不存在或不可退款');
            }

            // 当前订单已退款总金额
            $refunded_money = $order['refund_fee'];
            // 剩余可退款金额
            $refund_surplus_money = $order->pay_fee - $refunded_money;
            // 如果退款金额大于订单支付总金额
            if ($refund_money > $refund_surplus_money) {
                $this->error('退款总金额不能大于实际支付金额');
            }

            if($refund_money!=$refund_surplus_money){
                $this->error('必须全额退款');
            }

            if(in_array($order['refund_status'],[
                \app\admin\model\oil\order\Order::REFUND_STATUS_OK,
                \app\admin\model\oil\order\Order::REFUND_STATUS_FINISH,
            ])){
                $this->error('订单已退款，不能重复退款');
            }

            Db::transaction(function () use ($order, $refund_money, $refund_surplus_money) {
//                if($order['buyorgive']==1){
//                    // 退款完成
//                    $order->refund_status = \app\admin\model\oil\order\Order::REFUND_STATUS_FINISH;    // 退款完成
//                    $order->ext = json_encode($order->setExt($order, ['refund_time' => time()]));      // 退款完成时间
//                    $order->save();
//                    \addons\oil\model\OrderAction::operAdd($order, null, 'admin', '退款成功');
//
//                    $original_id=$order['original_id'];
//                    $order_original=Order::where('id',$original_id)->find();
//
//                    //转赠订单退还原订单的支付总额
//                    $refund_money=$refund_money>0?$refund_money:$order_original['total_fee'];
//
//                    \app\admin\model\oil\order\Order::startRefund($order_original, $refund_money, $this->auth->getUserInfo());//处理真正的订单退款
//                }else{
                    \app\admin\model\oil\order\Order::startRefund($order, $refund_money, $this->auth->getUserInfo(), '管理员操作退款');
//                }

            });
            return $this->success('操作成功', null);
        }
    }


    // 取消订单
    public function cancel($id)
    {
        if ($this->request->isAjax()) {
            $order = $this->model->where('id', $id)->nopay()->find();
            if (!$order) {
                $this->error('订单不存在或已取消');
            }
            $order = $order->doCancel($order, $this->auth->getUserInfo(), 'admin');
            return $this->success('操作成功', null, $order);
        }
    }

    // 编辑商家备注
    public function editMemo($id)
    {
        if ($this->request->isAjax()) {
            $memo = $this->request->post('memo');

            $order = $this->model->withTrashed()->where('id', $id)->find();
            if (!$order) {
                $this->error('订单不存在');
            }

            $order->memo = $memo;
            $order->save();

            \addons\oil\model\OrderAction::operAdd($order, $this->auth->getUserInfo(), 'admin', "修改备注：" . $memo);

            return $this->success('操作成功', null, $order);
        }
    }


    // 获取订单操作记录
    public function actions($id)
    {
        $actions = \app\admin\model\oil\order\OrderAction::with('oper')->where('order_id', $id)->order('id', 'desc')->select();

        foreach ($actions as $key => $action) {
            $action = $action->toArray();
            if ($action['oper_type'] == 'admin') {
                $oper = [
                    'id' => $action['oper_id'],
                    'name' => $action['oper'] ? $action['oper']['nickname'] : ''
                ];
            } else if ($action['oper_type'] == 'user') {
                $oper = [
                    'id' => $action['oper_id'],
                    'name' => '用户'
                ];
            } else if ($action['oper_type'] == 'system') {
                $oper = [
                    'id' => $action['oper_id'],
                    'name' => '系统'
                ];
            } else if ($action['oper_type'] == 'store') {
                $store_user=(new \app\admin\model\User())->where('id',$action['oper_id'])->find();
                $oper = [
                    'id' => $action['oper_id'],
                    'name' => "加油员:".$store_user['mobile']
                ];
            }else {
                $oper = null;
            }

            $action['oper'] = $oper;
            $actions[$key] = $action;
        }

        return $this->success('操作成功', null, $actions);
    }


    // 构建查询条件
    private function buildSearchOrder()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $status = isset($filter['status']) ? $filter['status'] : 'all';
        $aftersale_sn = isset($filter['aftersale_sn']) ? $filter['aftersale_sn'] : '';
        $nickname = isset($filter['nickname']) ? $filter['nickname'] : '';
        $mobile = isset($filter['user_phone']) ? $filter['user_phone'] : '';
        $store_id = isset($filter['store_id']) ? $filter['store_id'] : 'all';

        $name = $this->model->getQuery()->getTable();
        $tableName = $name . '.';

        $orders = $this->model->withTrashed();

        if ($nickname || $mobile) {
            $orders = $orders->whereExists(function ($query) use ($nickname, $mobile, $tableName) {
                $userTableName = (new \app\admin\model\User())->getQuery()->getTable();

                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . 'user_id');

                if ($nickname) {
                    $query = $query->where('nickname', 'like', "%{$nickname}%");
                }

                if ($mobile) {
                    $query = $query->where('mobile', 'like', "%{$mobile}%");
                }

                return $query;
            });
        }

        // 售后单号
        if ($aftersale_sn) {
            $orders = $orders->whereExists(function ($query) use ($aftersale_sn, $tableName) {
                $itemTableName = (new \app\admin\model\oil\order\Aftersale())->getQuery()->getTable();
                $query->table($itemTableName)->where($itemTableName . '.order_id=' . $tableName . 'id')
                    ->where('aftersale_sn', $aftersale_sn);
            });
        }


        // 快递方式 || 商品类型 (同一个表，写在一起)
        if ($store_id != 'all') {
            $orders = $orders->whereExists(function ($query) use ( $store_id, $tableName) {
                if ($store_id != 'all') {
                    // 门店订单
                    if ($store_id) {
                        $query = $query->where('store_id', $store_id);
                    } else {
                        $query = $query->where('store_id', '<>', 0);
                    }
                }
                return $query;
            });
        }

        // 订单状态
        if ($status != 'all') {
            if (in_array($status, ['invalid', 'cancel', 'nopay', 'nosend', 'noget', 'nocomment', 'aftersale', 'refund', 'payed', 'finish','share'])) {
                if (in_array($status, ['nosend', 'noget', 'nocomment', 'aftersale', 'refund'])) {
                    $orders = $orders->payed();
                }

                $status = $status == 'refund' ? 'refundStatus' : $status;

                if ($store_id != 'all' && in_array($status, ['nosend', 'noget', 'nocomment', 'aftersale', 'refundStatus'])) {
                    // 查询门店订单,需要增加 store_id 进行查询
                    $status = 'store' . ucfirst($status);
                    $orders = $orders->{$status}($store_id);
                } else {
                    // 所有订单
                    $orders = $orders->{$status}();
                }
            }
        }

        return $orders;
    }
}
